﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using XCommunity.Views;
using System.Web;

namespace XCommunity.Web.UI
{
  public static class ViewBinder
  {


    public static object EvalView( this Control container, string expression )
    {
      return Eval( container.GetView(), expression.Split( '.' ) );
    }



    public static string EvalView( this Control container, string expression, string format )
    {

      if ( container == null )
        return "";


      var value = EvalView( container, expression );

      if ( value == null )
        return null;

      if ( string.IsNullOrEmpty( format ) )
        return value.ToString();

      return string.Format( format, value );
    }



    public static string EvalView( this Control container, string expression, string format, bool attributeEncodeMode )
    {
      if ( attributeEncodeMode )
        return HttpUtility.HtmlAttributeEncode( EvalView( container, expression, format ) );
      else
        return HttpUtility.HtmlEncode( EvalView( container, expression, format ) );
    }



    private static object Eval( object container, string[] expressionParts )
    {
      object propertyValue = container;
      for ( int i = 0; ( i < expressionParts.Length ) && ( propertyValue != null ); i++ )
      {
        propertyValue = GetValue( propertyValue, expressionParts[i] );
      }
      return propertyValue;
    }



    public static object GetValue( object container, string propertyName )
    {
      var view = container as ViewObject;
      if ( view != null )
        return view.GetValue( propertyName );
      else
        return DataBinder.GetPropertyValue( container, propertyName );
    }











    public static ViewObject GetView( object container )
    {
      if ( container == null )
        return null;

      var view = container as ViewObject;
      if ( view != null )
        return view;


      var control = container as Control;
      if ( control != null )
        return GetView( control );

      return null;
    }


    public static ViewObject GetView( this Control control )
    {
      if ( control == null )
        return null;


      var presenter = control as IPresenter;
      if ( presenter != null )
        return presenter.View;


      var dataItem = DataBinder.GetDataItem( control );
      if ( dataItem != null )
        return dataItem as ViewObject;


      return GetView( control.NamingContainer );
    }





    public static IPresenter GetPresenter( this Control control )
    {

      if ( control == null )
        return null;

      var presenter = control as IPresenter;
      if ( presenter != null )
        return presenter;

      return GetPresenter( control.NamingContainer );
    }

  }
}
